<template>
  <div class="dept-cascader">
    <el-cascader
      ref="dept"
      :options="options"
      v-model="checked"
      filterable
      :clearable="clearable"
      :disabled="disabled"
      :show-all-levels="false"
      :props="{
        children: 'children',
        label: 'NAME',
        value: 'dept_id',
        expandTrigger: 'hover',
        multiple: false,
        checkStrictly: true,
        emitPath: false,
      }"
      @change="handleChange"
    >
    </el-cascader>
  </div>
</template>

<script>
export default {
  props: {
    options: {
      type: Array,
      default: null,
    },
    defaultChecked: {
      type: [String, Number],
      default: -1,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    handleChange(val) {
      // let node = this.$refs.dept.getCheckedNodes()[0];
      // if (node) {
      //   this.$emit("change", { label: node.label, value: node.value });
      // } else {
      //   this.recursiveQuery(this.options, val);
      // }
      if (val) {
        this.recursiveQuery(this.options, val);
      } else {
        this.$emit("change", { label: "", value: "" });
      }
    },
    recursiveQuery(options, matchTarget) {
      options.forEach((item) => {
        if (item.dept_id == matchTarget) {
          this.$emit("change", { label: item.NAME, value: item.dept_id });
          return;
        }
        if (item.children) {
          this.recursiveQuery(item.children, matchTarget);
        } else {
          return;
        }
      });
    },
  },
  computed: {
    checked: {
      get() {
        return this.defaultChecked;
      },
      set(val) {
        // this.$emit("defaultChecked", val);
      },
    },
  },
};
</script>

<style lang="scss" scoped></style>
